import os
import json
from functools import partial
from pathlib import Path
from tencentcloud.ocr.v20181119.models import VatInvoiceOCRResponse

from invoice2data import extract_data
from invoice2data.extract.loader import read_templates
import tempfile
from PIL import Image
import poocr
from datetime import datetime, date


def image_to_pdf(image_path, output_pdf_path=None):
    """将图片转换为PDF"""
    if output_pdf_path is None:
        # 生成临时PDF路径
        output_pdf_path = tempfile.mktemp(suffix='.pdf')

    # 打开图片并转换为PDF
    image = Image.open(image_path)
    image.save(output_pdf_path, "PDF")
    return output_pdf_path
# sourcefile = image_to_pdf(os.path.normpath(r'C:\\Users\\Administrator\\Downloads\\invoice.jpg'), os.path.normpath(r'D:\Uploads\test.pdf'))

def parse_date(dt):
    # if isinstance(dt, (date, datetime)):
    #     return dt
    formats = [
        "%Y-%m-%d",  # 2025-01-01
        "%Y/%m/%d",  # 2025/01/01
        "%Y年%m月%d日"  # 2025年01月01日
    ]
    for fmt in formats:
        try:
            # 尝试解析日期字符串
            dt = datetime.strptime(dt, fmt)
            # 返回日期部分（不含时间）
            return dt
        except ValueError:
            continue  # 如果格式不匹配，尝试下一种格式
    # 所有格式都不匹配时抛出异常
    raise ValueError(f"日期格式无效: '{dt}'。支持的格式: YYYY-MM-DD, YYYY/MM/DD, YYYY年MM月DD日")


def extract_invoice_info_By_invoice2data(sourcefile:str):
    """
    提取发票信息
    """
    templatefile = os.path.normpath(r'E:\Codes\python-demo\selenium\PDF_extractor\xky')
    data = extract_data(sourcefile,templates=read_templates(templatefile))
    return data

def extract_invoice_info_By_tencentCloud(sourcefile:str):
    """
    提取发票信息
    """
    id = 'AKIDJrHUVp23sKbfW9eBqJYcT8bByayBD8rQ'
    key = 'Zu31pSu89yb1DCzYu41lIckhnfLo34sS'
    result = poocr.ocr.VatInvoiceOCR(img_path=sourcefile, id=id, key=key)
    # 访问具体字段
    # 转成 JSON 字符串，再转字典
    response_json = result.to_json_string()
    response_dict = json.loads(response_json)
    #print(response_dict['VatInvoiceInfos'])
    #print(response_dict['Items'])
    data = {}
    for d in response_dict['VatInvoiceInfos']:
        # print(d)
        if d['Name'] == "发票号码":
            data['invoice_number'] = d['Value']
        elif d['Name'] == "合计金额":
            data['amount'] = d['Value'].replace('￥', '')
        elif d['Name'] == "销售方名称":
            data['seller_name'] = d['Value']
        elif d['Name'] == "购买方名称":
            data['buyer_name'] = d['Value']
        elif d['Name'] == "发票类型":
            data['issuer'] = d['Value']
        elif d['Name'] == "开票日期":
            data['invoice_date'] = parse_date(d['Value'])
    return data

def main():
    """
    主函数
    """
    sourcefile = os.path.normpath(r'C:\Users\Administrator\Downloads\invoice.jpg')
    #sourcefile = os.path.normpath(r'E:\Decl\VBA程序\发票信息提取\辰飞发票(2).pdf')
    if Path(sourcefile).suffix == '.pdf':
        handlers=[
            partial(extract_invoice_info_By_invoice2data, sourcefile),
            partial(extract_invoice_info_By_tencentCloud, sourcefile),
        ]
    else:
        handlers=[
            partial(extract_invoice_info_By_tencentCloud, sourcefile),
            partial(extract_invoice_info_By_invoice2data, sourcefile),
        ]
    for handler in handlers:
        try:
            data = handler()
            print(data)
        except Exception as e:
            print(f"Error: {e}")
            continue
        break

if __name__ == "__main__":
    main()
